package main

import (
	"fmt"
	"math/rand"
	"time"
)

//2000毫秒内随机间隔向通道写入，并返回这个通道并限制为只出不进
func msgGen(name string) <-chan string {
	ch := make(chan string)
	go func() {
		i := 0
		for {
			time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond) //2000毫秒内随机sleep
			ch <- fmt.Sprintf("%s message:%d", name, i)
			i++
		}
	}()
	return ch
}

func fanIn(ch1 <-chan string, ch2 <-chan string) <-chan string {
	ch := make(chan string)
	go func() {
		for {
			ch <- <-ch1
		}

	}()
	go func() {
		for {
			ch <- <-ch2
		}
	}()

	return ch
}

func fanIn2(chs ...<-chan string) <-chan string {
	ch := make(chan string)
	for _, c := range chs {
		//*
		go func() {
			for {
				ch <- <-c
			}
		}()
	}

	return ch
}
func main() {

	ch1 := msgGen("service1")
	ch2 := msgGen("service2")
	//ch3 := msgGen("service3")
	ch := fanIn(ch1, ch2) //将两个通道汇集到一个通道里
	//ch := fanIn2(ch1, ch2, ch3)//更多通道情况的处理方式
	//str := ""
	for {
		//select {
		//case str = <-ch1:
		//	fmt.Println(str)
		//case str = <-ch2:
		//	fmt.Println(str)
		//}

		fmt.Println(<-ch)

		//阻塞读取
		//fmt.Println(<-ch1)
		//fmt.Println(<-ch2)

		//非阻塞读取
		//select {
		//case str := <-ch2:
		//	fmt.Println(str)
		//default:
		//	fmt.Println("service2 no message")
		//}

		//非阻塞读取
		//select {
		//case str := <-ch2:
		//	fmt.Println(str)
		//case <-time.After(time.Second):
		//	fmt.Println("service2 timeout")
		//	//default:
		//	//	fmt.Println("service2 no message")
		//}
	}

}
